package org.stvd.service.admin.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.stvd.common.SecurityUserHolder;
import org.stvd.common.enums.UserLoginTypeEnum;
import org.stvd.common.enums.VerifyCodeTypeEnum;
import org.stvd.common.utils.PwdUtil;
import org.stvd.common.utils.ServiceResult;
import org.stvd.core.dto.QueryResult;
import org.stvd.core.util.DateUtil;
import org.stvd.core.util.IdWorker;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.Department;
import org.stvd.entities.admin.Guids;
import org.stvd.entities.admin.Params;
import org.stvd.entities.admin.Roles;
import org.stvd.entities.admin.SysLogoutInfo;
import org.stvd.entities.admin.UserBase;
import org.stvd.entities.admin.UserConfig;
import org.stvd.entities.admin.UserLogin;
import org.stvd.entities.admin.Users;
import org.stvd.entities.common.VerifyTmp;
import org.stvd.entities.common.VerifyTmpPK;
import org.stvd.repository.admin.DepartmentDao;
import org.stvd.repository.admin.GuidsDao;
import org.stvd.repository.admin.ParamsDao;
import org.stvd.repository.admin.RolesDao;
import org.stvd.repository.admin.SysLogoutInfoDao;
import org.stvd.repository.admin.UserBaseDao;
import org.stvd.repository.admin.UserConfigDao;
import org.stvd.repository.admin.UserDepDao;
import org.stvd.repository.admin.UserGuidDao;
import org.stvd.repository.admin.UserLoginDao;
import org.stvd.repository.admin.UserRoleDao;
import org.stvd.repository.admin.UsersDao;
import org.stvd.repository.common.VerifyTmpDao;
import org.stvd.service.admin.DepartmentService;
import org.stvd.service.admin.RolesService;
import org.stvd.service.admin.UsersService;
import org.stvd.service.base.impl.BaseServiceImpl;
import org.stvd.service.common.VerifyTmpService;

@Service("usersService")
public class UsersServiceImpl extends BaseServiceImpl<Users> implements UsersService {

    @Resource(name = "UsersDao")
    private UsersDao usersDao;
    @Resource(name = "UserBaseDao")
    private UserBaseDao userBaseDao;
    @Resource(name = "RolesDao")
    private RolesDao rolesDao;
    @Resource(name = "UserDepDao")
    private UserDepDao userDepDao;
    @Resource(name = "UserRoleDao")
    private UserRoleDao userRoleDao;
    @Resource(name = "UserGuidDao")
    private UserGuidDao userGuidDao;
    @Resource(name = "GuidsDao")
    private GuidsDao guidsDao;
    @Resource(name = "DepartmentDao")
    private DepartmentDao departmentDao;
    @Resource(name = "ParamsDao")
    private ParamsDao paramsDao;
    @Resource(name = "UserLoginDao")
    private UserLoginDao userLoginDao;
    @Resource(name = "UserConfigDao")
    private UserConfigDao userConfigDao;
    @Resource(name = "VerifyTmpDao")
    private VerifyTmpDao verifyTmpDao;
    @Resource(name = "SysLogoutInfoDao")
    private SysLogoutInfoDao sysLogoutInfoDao;
    
    @Autowired
    private RolesService rolesService; //系统角色Service
    @Autowired
    private DepartmentService departmentService; //系统机构Service
    @Autowired
    private VerifyTmpService verifyTmpService; //临时信息验证
    
    @Override
    public Users findById(String userId) {
        if(StringUtil.isEmpty(userId)) {
            return null;
        }
        Users users = usersDao.findByPk(Users.class, userId);
        if(users==null) {
            return null;
        }
        UserBase userBase = userBaseDao.findByPk(UserBase.class, userId);
        users.setUserBase(userBase);
        List<Department> departmentList = departmentDao.findAllDepByUid(userId);
        users.setDepartmentList(departmentList);
        List<Roles> roleList = rolesDao.findAllRoleByUid(userId);
        users.setRoleList(roleList);
        List<Guids> guidList = guidsDao.listGuidByUserId(userId);
        users.setGuidList(guidList);
        List<UserLogin> userLoginList = userLoginDao.findUserLoginByUserId(userId);
        users.setUserLoginList(userLoginList);
        return users;
    }
    
    @Override
    public QueryResult<Users> getUsersQueryResult(int start, int limit, String loginCode, 
        String userName, List<String> depIds, String roleId, String guid) {
        QueryResult<Users> queryResult = usersDao.getUsersQueryResult(start, limit, loginCode, userName, depIds, roleId, guid);
        return queryResult;
    }

    @Override
    @Transactional
    public void updatePwd(String userid, String curPwd, String newPwd) throws Exception {
        Users user = usersDao.findByPk(Users.class, userid);
        if (user != null) {
            if (user.getPwd().equals(curPwd)) {
                user.setPwd(newPwd);
                update(user);
            } else {
                throw new Exception("原密码不正确！");
            }
        } else {
            throw new Exception("用户编号" + userid + "不存在！");
        }

    }

    @Override
    @Transactional
    public void updatePwd(String userid, String newPwd) throws Exception {
        Users user = usersDao.findByPk(Users.class, userid);
        if (user != null) {
            user.setPwd(newPwd);
            update(user);
        } else {
            throw new Exception("用户编号" + userid + "不存在！");
        }

    }

    @Override
    @Transactional
    public void delete(String userid, String guid) {
        usersDao.delete(Users.class, userid);
        userLoginDao.deleteByUserId(userid);
        userBaseDao.delete(UserBase.class, userid);
        userConfigDao.delete(UserConfig.class, userid);
        userRoleDao.insert(userid, null, guid);
        userDepDao.insert(userid, null, guid);
    }

    @Override
    @Transactional
    public void insert(Users user, String[] roleids, String[] depids, UserLogin userLogin, UserBase userBase, String guid) throws Exception {
        if (usersDao.findByPk(Users.class, user.getUserId()) != null) {
            throw new Exception("用户编号‘" + user.getUserId() + "’已经存在！");
        } else {
            usersDao.insert(user);
            userRoleDao.insert(user.getUserId(), roleids, guid);
            userDepDao.insert(user.getUserId(), depids, guid);
            userLoginDao.insert(userLogin);
            userBaseDao.insert(userBase);
        }
    }

    @Override
    @Transactional
    public void insert(Users user, String[] roleIds, String[] depIds, String[] guids,  UserLogin userLogin, UserBase userBase,String guid) throws Exception {
        if (usersDao.findByPk(Users.class, user.getUserId()) != null) {
            throw new Exception("用户编号‘" + user.getUserId() + "’已经存在！");
        } else {
            usersDao.insert(user);
            userRoleDao.insert(user.getUserId(), roleIds, guid);
            userDepDao.insert(user.getUserId(), depIds, guid);
            userGuidDao.insert(user.getUserId(), guids);
            userLoginDao.insert(userLogin);
            userBaseDao.insert(userBase);
        }
    }
    
    @Override
    @Transactional
    @CacheEvict(value = "adminCache", allEntries = true)
    public void update(Users users, String[] guids) {
        List<UserLogin> userLogins = userLoginDao.findUserLoginByUserId(users.getUserId());
        if(userLogins!=null && userLogins.size()>0) {
            for (UserLogin userLogin : userLogins) {
                userLogin.setLoginStatus("T".equals(users.getEnable()) ? "1":"0");
                userLoginDao.update(userLogin);
            }
        }
        usersDao.update(users);
        userGuidDao.insert(users.getUserId(), guids);
    }

    @Override
    @Transactional
    @CacheEvict(value = "adminCache", allEntries = true)
    public void update(String[] roleids, String[] depids, String userId, String guid) {
        userRoleDao.insert(userId, roleids, guid);
        userDepDao.insert(userId, depids, guid);
    }
    
    @Override
    @Transactional
    public String clrPwd(String userid, String guid) {
        Users user = usersDao.findByPk(Users.class, userid);
        String resultMsg = "";
        List<Params> params = paramsDao.findByParamName(guid, "ACCOUNT_DEFAULT_PASS");
        String clrPwd = "666666";
        if(params!=null && params.size()==1) {
            clrPwd = params.get(0).getParamValue();
        }
        if (user != null) {
            user.setPwd(StringUtil.encrypt(clrPwd, userid + DateUtil.Y2NO_FORMAT.format(user.getIndate())));
            usersDao.update(user);
            resultMsg = "密码还原成功！新密码为：【"+clrPwd+"】";
        }else {
            resultMsg = "用户信息查询失败";
        }
        return resultMsg;
    }

    @Override
    public List<String> getParentDepids(Department department) {
        List<String> list = new ArrayList<String>();
        Department parentDep = departmentDao.findByPk(Department.class, department.getUpperId());
        if (parentDep != null) {
            list.add(parentDep.getDepId());
            list.addAll(getParentDepids(parentDep));
        }
        return list;
    }

    @Override
    public List<Users> findUsers(String userid, String dep_id, String dep_type, String guid) {
        return usersDao.findUsers(userid, dep_id, dep_type, guid);
    }

    /**
     * 设置用户的扩展信息，并返回用户的关键数据
     */
    @Override
    public Map<String, Object> setUserDetailPlus(String userid) {
        Map<String, Object> remarks = new HashMap<String, Object>();
        remarks.put("userBase", userBaseDao.findByPk(UserBase.class, userid));
        return remarks;
    }

    /**
     * 插入UserLogin
     */
    @Transactional
    public void insertUserLogin(UserLogin userLogin){
        userLoginDao.insert(userLogin);
    }
    
    /**
     * 更新UserLogin
     */
    @Transactional
    public void updateUserLogin(UserLogin userLogin) {
        userLoginDao.update(userLogin);
    }
    
    /**
     * 更新UserConfig
     */
    @Transactional
    public void updateUserConfig(UserConfig userConfig) {
        if(userConfig!=null) {
            userConfigDao.update(userConfig);
        }
    }
    
    /**
     * 根据用户ID及账号类型删除账号信息
     */
    @Transactional
    public void deleteByIdType(String userid,String loginType) {
        userLoginDao.deleteByIdType(userid,loginType);
    }
    
    /**
     * 根据登陆账号获取用户登陆账号表信息
     */
    @Override
    public UserLogin findUserLoginByLoginAccount(String loginAccount) {
        return userLoginDao.findUserLoginByLoginAccount(loginAccount);
    }
    
    /**
     * 获取所有登录账号列表
     */
    @Override
    public List<UserLogin> listAllUserLogin() {
        return userLoginDao.findAll(UserLogin.class);
    }
    
    /**
     * 获取用户所有登录账号
     */
    public List<UserLogin> findUserLoginByUserId(String userId) {
        return userLoginDao.findUserLoginByUserId(userId);
    }
    
    /**
     * 根据登陆账号类型及登陆账号获取用户登陆账号信息
     */
    public UserLogin findUserLoginByTypeAccount(String loginType, String loginAccount){
        return userLoginDao.findUserLoginByTypeAccount(loginType,loginAccount);
    }
    
    /**
     * 根据userID及账号类型登陆账号信息
     */
    public UserLogin findUserLoginByIDType(String userID, String loginType){
        return userLoginDao.findUserLoginByIDType(userID,loginType);
    }

    @Override
    public ServiceResult<Map<String, Object>> bindingUserMobile(String userId, String mobileStr, String validateCode) {
        ServiceResult<Map<String, Object>> serviceResult = new ServiceResult<>();
        if(StringUtil.isEmpty(userId) || StringUtil.isEmpty(mobileStr) || StringUtil.isEmpty(validateCode)) {
            serviceResult.setParamError();
            return serviceResult;
        }
        VerifyTmp  verifyTmp = verifyTmpDao.findByPK(new VerifyTmpPK(mobileStr, VerifyCodeTypeEnum.Bind.getValue()));
        if(verifyTmp==null) {
            serviceResult.setParamError();
            return serviceResult;
        }
        String vCode = verifyTmp.getVerifyCode();
        if(!validateCode.equals(vCode)) {
            serviceResult.setDataError("验证码错误！");
            return serviceResult;
        }
        if((DateUtil.getSystemDate().getTime()
                - verifyTmp.getInputDatetime().getTime()) > (1000*60*10)) {
            serviceResult.setDataError("验证码已失效，请重新获取！");
            return serviceResult;
        }
        UserLogin userLogin = userLoginDao.findUserLoginByLoginAccount(mobileStr);
        if(userLogin!=null) {
            serviceResult.setDataError("当前手机号码已绑定账号！");
            return serviceResult;
        }
        userLogin = userLoginDao.findUserLoginByIDType(userId, UserLoginTypeEnum.Mobile.getValue());
        if(userLogin==null) {
            userLogin = new UserLogin();
            userLogin.setId(StringUtil.getRandomUUID());
            userLogin.setUserId(userId);
            userLogin.setLoginType(UserLoginTypeEnum.Mobile.getValue());
            userLogin.setLoginStatus("1");
        }
        // 绑定账号
        userLogin.setLoginAccount(mobileStr);
        userLoginDao.update(userLogin);
        
        // 删除验证信息
        verifyTmpDao.deleteVerifyTmp(new VerifyTmpPK(mobileStr, VerifyCodeTypeEnum.Bind.getValue()));
        serviceResult.setMessage("绑定成功！");
        return serviceResult;
    }

    @Override
    public ServiceResult<Map<String, Object>> bindingUserEmail(String userId, String emailStr, String validateCode) {
        ServiceResult<Map<String, Object>> serviceResult = new ServiceResult<>();
        if(StringUtil.isEmpty(userId) || StringUtil.isEmpty(emailStr) || StringUtil.isEmpty(validateCode)) {
            serviceResult.setParamError();
            return serviceResult;
        }
        VerifyTmp  verifyTmp = verifyTmpDao.findByPK(new VerifyTmpPK(emailStr, VerifyCodeTypeEnum.Bind.getValue()));
        if(verifyTmp==null) {
            serviceResult.setParamError();
            return serviceResult;
        }
        String vCode = verifyTmp.getVerifyCode();
        if(!validateCode.equals(vCode)) {
            serviceResult.setDataError("验证码错误！");
            return serviceResult;
        }
        if((DateUtil.getSystemDate().getTime()
                - verifyTmp.getInputDatetime().getTime()) > (1000*60*10)) {
            serviceResult.setDataError("验证码已失效，请重新获取！");
            return serviceResult;
        }
        UserLogin userLogin = userLoginDao.findUserLoginByLoginAccount(emailStr);
        if(userLogin!=null) {
            serviceResult.setDataError("当前邮箱已绑定账号！");
            return serviceResult;
        }
        userLogin = userLoginDao.findUserLoginByIDType(userId, UserLoginTypeEnum.Email.getValue());
        if(userLogin==null) {
            userLogin = new UserLogin();
            userLogin.setId(StringUtil.getRandomUUID());
            userLogin.setUserId(userId);
            userLogin.setLoginType(UserLoginTypeEnum.Email.getValue());
            userLogin.setLoginAccount(emailStr);
            userLogin.setLoginStatus("1");
        }
        // 绑定账号
        userLogin.setLoginAccount(emailStr);
        userLoginDao.update(userLogin);
        
        // 删除验证信息
        verifyTmpDao.deleteVerifyTmp(new VerifyTmpPK(emailStr, VerifyCodeTypeEnum.Bind.getValue()));
        serviceResult.setMessage("绑定成功！");
        return serviceResult;
    }

    @Override
    public ServiceResult<Map<String, Object>> resetpwdForUserMobile(String mobileNumStr, 
        String verifyCodeStr, String newPassword, String confirmPassword) {
        ServiceResult<Map<String, Object>> serviceResult = new ServiceResult<>();
        if(StringUtil.isEmpty(mobileNumStr) || StringUtil.isEmpty(verifyCodeStr) || StringUtil.isEmpty(newPassword)) {
            serviceResult.setParamError();
            return serviceResult;
        }
        if(StringUtil.isEmpty(confirmPassword) || !confirmPassword.equals(newPassword)){
            serviceResult.setParamError("两次输入的密码不匹配！");
             return serviceResult;
         }
        String checkResult = PwdUtil.chechPwdStrength(newPassword);
        if(checkResult!=null) {
            serviceResult.setParamError(checkResult);
            return serviceResult;
        }
        VerifyTmp verifyTmp = verifyTmpDao.findByPK(new VerifyTmpPK(mobileNumStr, VerifyCodeTypeEnum.ResetPassword.getValue()));
        if(verifyTmp==null) {
            serviceResult.setParamError();
            return serviceResult;
        }
        String vCode = verifyTmp.getVerifyCode();
        if(!verifyCodeStr.equals(vCode)) {
            serviceResult.setDataError("验证码错误！");
            return serviceResult;
        }
        if((DateUtil.getSystemDate().getTime()
            - verifyTmp.getInputDatetime().getTime()) > (1000*60*10)) {
            serviceResult.setDataError("验证码已失效，请重新获取！");
            return serviceResult;
        }
        UserLogin userLogin = userLoginDao.findUserLoginByTypeAccount(UserLoginTypeEnum.Mobile.getValue(), mobileNumStr);
        if(userLogin==null) {
            serviceResult.setDataError("当前手机号未绑定相关账号！");
            return serviceResult;
        }
        String userId = userLogin.getUserId();
        Users users = usersDao.findByPk(Users.class, userId);
        if(users==null) {
            serviceResult.setDataError("用户账户获取失败！");
            return serviceResult;
        }
        String ymd = DateUtil.Y2NO_FORMAT.format(users.getIndate());
        users.setPwd(StringUtil.encrypt(newPassword, userId + ymd));
        users.setModifyDate(DateUtil.getSystemDate());
        usersDao.update(users);
        
        // 删除验证信息
        verifyTmpDao.deleteVerifyTmp(new VerifyTmpPK(mobileNumStr, VerifyCodeTypeEnum.ResetPassword.getValue()));
        serviceResult.setMessage("重置成功！");
        return serviceResult;
    }
    
    @Override
    public ServiceResult<Map<String, Object>> resetpwdForUserEmail(String emailNumStr, 
        String verifyCodeStr, String newPassword, String confirmPassword) {
        ServiceResult<Map<String, Object>> serviceResult = new ServiceResult<>();
        if(StringUtil.isEmpty(emailNumStr) || StringUtil.isEmpty(verifyCodeStr) || StringUtil.isEmpty(newPassword)) {
            serviceResult.setParamError();
            return serviceResult;
        }
        if(StringUtil.isEmpty(confirmPassword) || !confirmPassword.equals(newPassword)){
            serviceResult.setParamError("两次输入的密码不匹配！");
             return serviceResult;
         }
        String checkResult = PwdUtil.chechPwdStrength(newPassword);
        if(checkResult!=null) {
            serviceResult.setParamError(checkResult);
            return serviceResult;
        }
        VerifyTmp verifyTmp = verifyTmpDao.findByPK(new VerifyTmpPK(emailNumStr, VerifyCodeTypeEnum.ResetPassword.getValue()));
        if(verifyTmp==null) {
            serviceResult.setParamError();
            return serviceResult;
        }
        String vCode = verifyTmp.getVerifyCode();
        if(!verifyCodeStr.equals(vCode)) {
            serviceResult.setDataError("验证码错误！");
            return serviceResult;
        }
        if((DateUtil.getSystemDate().getTime()
            - verifyTmp.getInputDatetime().getTime()) > (1000*60*10)) {
            serviceResult.setDataError("验证码已失效，请重新获取！");
            return serviceResult;
        }
        UserLogin userLogin = userLoginDao.findUserLoginByTypeAccount(UserLoginTypeEnum.Email.getValue(), emailNumStr);
        if(userLogin==null) {
            serviceResult.setDataError("当前邮箱未绑定相关账号！");
            return serviceResult;
        }
        String userId = userLogin.getUserId();
        Users users = usersDao.findByPk(Users.class, userId);
        if(users==null) {
            serviceResult.setDataError("用户账户获取失败！");
            return serviceResult;
        }
        String ymd = DateUtil.Y2NO_FORMAT.format(users.getIndate());
        users.setPwd(StringUtil.encrypt(newPassword, userId + ymd));
        users.setModifyDate(DateUtil.getSystemDate());
        usersDao.update(users);
        
        // 删除验证信息
        verifyTmpDao.deleteVerifyTmp(new VerifyTmpPK(emailNumStr, VerifyCodeTypeEnum.ResetPassword.getValue()));
        serviceResult.setMessage("重置成功！");
        return serviceResult;
    }

    @Override
    public ServiceResult<Map<String, Object>> registAccountForUserMobile(String mobileStr, String userName, String validateCode, 
        String password, String confirmPassowrd, String defaultRoleCode, String DefaultDepCode, String guid, String url) {
        return registAccount(mobileStr, UserLoginTypeEnum.Mobile.getValue(), userName, validateCode, password, confirmPassowrd, 
            defaultRoleCode, DefaultDepCode, guid, url);
    }
    
    @Override
    @Transactional
    public ServiceResult<Map<String, Object>> registAccount(String loginCode, String loginType, String userName,
        String validateCode, String password, String confirmPassowrd, String defaultRoleCode, String DefaultDepCode,
        String guid, String url) {
        ServiceResult<Map<String, Object>> serviceResult = new ServiceResult<>();
        // 提交数据校验 
        if ((StringUtil.isEmpty(loginCode) || (StringUtil.isEmpty(loginType)) || StringUtil.isEmpty(userName)) 
            || (StringUtil.isEmpty(password)) || (StringUtil.isEmpty(confirmPassowrd)) || (StringUtil.isEmpty(defaultRoleCode))
            ||  (StringUtil.isEmpty(DefaultDepCode)) || (StringUtil.isEmpty(guid))) {
            serviceResult.setParamError("所有注册项都必填");
            return serviceResult;
        }
        if (!password.equals(confirmPassowrd)) {
            serviceResult.setParamError("两次输入的密码不匹配!");
            return serviceResult;
        }
        String checkResult = PwdUtil.chechPwdStrength(password, loginCode);
        if(checkResult!=null) {
            serviceResult.setParamError(checkResult);
            return serviceResult;
        }
        UserLogin loginAccount = this.findUserLoginByLoginAccount(loginCode);
        if (loginAccount != null) {
            serviceResult.setParamError("当前"+UserLoginTypeEnum.getName(loginType)+"已注册");
            return serviceResult;
        }

        if(UserLoginTypeEnum.Mobile.getValue().contentEquals(loginType)) {
            //验证短信验证码 
            VerifyTmpPK verifyTmpPK = new VerifyTmpPK(loginCode, VerifyCodeTypeEnum.Regist.getValue());
            VerifyTmp verifyTemp = verifyTmpService.findByPK(verifyTmpPK);
            if (verifyTemp == null) {
                serviceResult.setParamError("短信验证码已失效");
                return serviceResult;
            }
            if ((DateUtil.getSystemDate().getTime() - verifyTemp.getInputDatetime().getTime()) > (1000 * 60 * 10)) {
                verifyTmpService.deleteVerifyTmp(verifyTmpPK);
                serviceResult.setParamError("短信验证码已失效");
                return serviceResult;
            }
            if (!(validateCode.equals(verifyTemp.getVerifyCode()))) {
                serviceResult.setParamError("短信验证码不正确");
                return serviceResult;
            }
            verifyTmpService.deleteVerifyTmp(verifyTmpPK);
        }

        String userId = StringUtil.getRandomUUID();
        String roleId = null;
        String depId = null;
        Roles roles = rolesService.getRolesByRoleCode(defaultRoleCode, guid);
        if (roles != null) {
            roleId = roles.getRoleId();
        }
        Department department = departmentService.getDepartmentByDepCode(DefaultDepCode, guid);
        if (department != null) {
            depId = department.getDepId();
        }
        // 注册用户拥有角色
        String[] roleIdArray = new String[] {roleId};
        // 注册用户所在机构
        String[] depIdArray = new String[] {depId};
        // 用户登录账号
        UserLogin userLogin = new UserLogin();
        userLogin.setId(StringUtil.getRandomUUID());
        userLogin.setUserId(userId);
        userLogin.setLoginAccount(loginCode);
        userLogin.setLoginType(loginType);
        // 用户基本信息
        UserBase userBase = new UserBase();
        userBase.setUserId(userId);
        userBase.setNickName(userName);
        // 用户安全账户
        Date indate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(indate);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        String ymd = DateUtil.Y2NO_FORMAT.format(calendar.getTime());

        Users users = new Users();
        users.setUserId(userId);
        users.setUname(userName);
        users.setEnable("T");
        users.setIndate(calendar.getTime());
        users.setModifyDate(DateUtil.getSystemDate());
        users.setPwd(StringUtil.encrypt(password, userId + ymd));
        try {
            this.insert(users, roleIdArray, depIdArray, userLogin, userBase, guid);
            rolesService.insertUserRole(userId, defaultRoleCode);
            departmentService.insertUserDep(userId, DefaultDepCode);
            //更新用户配置相关
            UserConfig userConfig = new UserConfig();
            userConfig.setUserId(userId);
            userConfig.setUserSourceUrl(url);
            userConfigDao.update(userConfig);
        } catch (Exception e) {
            e.printStackTrace();
            serviceResult.setDataError("账户注册异常，异常原因："+ e.getMessage());
            return serviceResult;
        }
        serviceResult.setMessage("注册成功！");
        return serviceResult;
    }
    
    @Override
    public void changeUserStatus(String userId, String status) {
        Users users = usersDao.findByPk(Users.class, userId);
        if(users!=null && !status.equals(users.getEnable())) {
            users.setEnable(status);
            users.setModifyDate(DateUtil.getSystemDate());
            usersDao.update(users);
        }
    }

    @Override
    @Transactional
    public ServiceResult<Map<String, Object>> delUser(String userId) {
        ServiceResult<Map<String, Object>> serviceResult = new ServiceResult<>();
        if (userId.equals(SecurityUserHolder.getCurrentUserid())) {
            serviceResult.setDataError("不能注销用户自己账号！");
            return serviceResult;
        }
        Users users = usersDao.findByPk(Users.class, userId);
        if (users == null) {
            serviceResult.setParamError();
            return serviceResult;
        }
        List<UserLogin> userLoginList = userLoginDao.findUserLoginByUserId(userId);
        for (UserLogin userLogin : userLoginList) {
            SysLogoutInfo sysLogoutInfo = new SysLogoutInfo();
            sysLogoutInfo.setLogoutId(IdWorker.getInstance().nextId());
            sysLogoutInfo.setUserId(userLogin.getUserId());
            sysLogoutInfo.setLoginType(userLogin.getLoginType());
            sysLogoutInfo.setLoginAccount(userLogin.getLoginAccount());
            sysLogoutInfo.setOperName(SecurityUserHolder.getCurrentUserid());
            sysLogoutInfo.setOperTime(DateUtil.getSystemDate());
            sysLogoutInfoDao.insert(sysLogoutInfo);
        }
        userLoginDao.deleteByUserId(userId);
        changeUserStatus(userId, "F");
        serviceResult.setMessage("账号注销完成！");
        return serviceResult;
    }
}
